/*****************************************************************************
 *   Copyright 2005 Tim A Wang
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 ****************************************************************************/
package com.jb.database.metamodel;

import com.jb.framework.DataSourceManager;

import com.jb.framework.database.SelectDBCommand;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class Database extends BaseDatabaseEntity {
    private Log log = LogFactory.getLog(getClass().getName());
    static Database db = null;
    String productName;
    int majorVersion;
    int minorVersion;
    private Schema schema;
    private String schemaName;

    public int getMajorVersion() {
        return majorVersion;
    }

    public void setMinorVersion(int minorVersion) {
        this.minorVersion = minorVersion;
    }

    public int getMinorVersion() {
        return minorVersion;
    }

    public void setProductName(String productName) {
        this.productName = productName;
    }

    public String getProductName() {
        return productName;
    }

    public Schema getSchema() {
        return schema;
    }

    public void setSchemaName(String schemaName) {
        schema = (Schema) getChildByTypeAndName(Schema.class, schemaName);
        if (schema == null) {
            schema = new Schema(schemaName);
            addChild(schema);
        }
    }

    public List getSchemas() {
        populate();
        return this.getChildrenByType(Schema.class);
    }

    public String getSchemaName() {
        return schemaName;
    }

    public List getTables() throws SQLException {
        setSchemaName("default");

        return schema.getTables("%");
    }

    public List getTables(String schemaName, String filter)
        throws SQLException {
        setSchemaName(schemaName);

        return schema.getTables(filter);
    }

    public List getViews(String schemaName, String filter)
        throws SQLException {
        setSchemaName(schemaName);

        return schema.getViews(filter);
    }

    public void assign(ResultSet crs) throws SQLException {
    }

    public void createSchema(String schemaName) {
        if (schema != null) {
            executeSQL("create database " + schemaName);
            this.populate();
        }
    }

    public void deleteSchema(String schemaName) {
        schema = (Schema) getChildByTypeAndName(Schema.class, schemaName);

        if (schema != null) {
            executeSQL("drop database " + schemaName);
            this.populate();
        }
    }

    public void setMajorVersion(int majorVersion) {
        this.majorVersion = majorVersion;
    }

    private ResultSet getSchemas(Connection conn) {
        try {
            String _listDB = "SHOW DATABASES";
            SelectDBCommand stmt = new SelectDBCommand(_listDB, null);
            stmt.execute(conn);
            return stmt.getResultSet();
        } catch (SQLException e) {
            try {
                return conn.getMetaData().getSchemas();
            } catch (SQLException _e) {
                if(log.isErrorEnabled())
                    log.error(this, _e);

            }
        }
        return null;
    }
    
    public void populate(Connection conn) {
        ResultSet rs = null;
        this.getChildren().clear();
        try {
            rs = getSchemas(conn); 
            if(rs!=null)
            {
                while (rs.next()) {
                    Schema schema = new Schema(rs.getString(1));
                    addChild(schema);
                }
                rs.close();
            }
            rs = null;
        } catch (Exception e) {
            if(log.isErrorEnabled())
                log.error(this, e);
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (Exception e) {
                    if(log.isErrorEnabled())
                        log.error(this, e);
                }
            }
        }
    }
    public void populate() {
        Connection conn = null;
        try {
            conn = DataSourceManager.getConnection(this);
            populate(conn);
            conn.commit();
        }catch (Exception e) {
            if(log.isErrorEnabled())
                log.error(this, e);
        } finally {
            if(conn!=null)
                DataSourceManager.releaseConnection(this, conn);
        }
    }
}
